<?php
class Frontend_Controller extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
        if(!$this->config->item('public')){
            redirect(base_url());
        }else{
            $this->load->driver('session');
            $this->load->library('Assets');
            
            if ($this->session->userdata('session_id') === FALSE) {
                $data_ses=array(
                    "language" => 'en',
                );
                $this->session->set_userdata($data_ses);
            }
            $this->render_lang();
            $this->render_translate(TRUE, TRUE);
        }
    }

    public function _remap($method, $params = array()){
       if (method_exists($this, $method))
           {
            return call_user_func_array(array($this, $method), $params);
        }
        
        $this->show404();
    }

    public function show404(){
        $this->output->set_status_header('404');
        $data['title'] = 'Không tìm thấy trang';
        $this->parser->parse("error/error_404.tpl", NULL, $data);
    }

    public function render_lang($cache_delete = FALSE, $registry_delete = FALSE){
        if($cache_delete){
            $this->db->cache_delete_all();
        }
        if($registry_delete){
            $this->registry->delete('language');
        }
        $this->db->cache_on();
        $dataLang = $this->db->get('tpt_language')->result_array();
        if(!empty($dataLang)){
            if(!$this->registry->has('language')){
                $this->registry->set('language', $dataLang);
            }
        }
        $this->db->cache_off();
    }

    public function render_translate($cache_delete = FALSE, $registry_delete = FALSE){
        if($cache_delete){
            $this->db->cache_delete_all();
        }
        if($registry_delete){
            $this->registry->delete('translate');
        }
        $this->db->cache_on();
        $dataTranslate = $this->db->select('word,lang_code,translate')->get('tpt_translate')->result_array();
        if(!empty($dataTranslate)){
            if(!$this->registry->has('translate')){
                $translates = array();
                foreach($dataTranslate as $item){
                    $translates[$item['lang_code']][$item['word']] = $item['translate'];
                }
                $this->registry->set('translate', $translates);
            }
        }
        $this->db->cache_off();
    }
}
